<template>
  <div class="table-page">
    <CommonTable
        ref="tableRef"
        :columns="tableColumns"
        :config="tableConfig"
        :api="apiConfig"
        @add="handleAdd"
        @edit="handleEdit"
        @selection-change="handleSelectionChange"
    >
      <!-- 自定义数据库类型列 -->
      <template #dbType="{ row }">
        <el-tag :type="getDbTypeTagType(row.dbType)">{{ getDbTypeName(row.dbType) }}</el-tag>
      </template>

      <!-- 自定义状态列 -->
      <template #status="{ row }">
        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
          {{ row.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </template>

      <!-- 自定义操作列 -->
      <template #actions="{ row }">
        <el-button type="primary" size="small" @click="testConnection(row)" :loading="testingId === row.id">
          测试连接
        </el-button>
        <el-button type="warning" size="small" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
    </CommonTable>

    <!-- 数据源表单弹窗 -->
    <CommonForm
        :columnsPerRow="1"
        ref="formRef"
        v-model:visible="showForm"
        :fields="formFields"
        :data="currentDatasource"
        :title="isEdit ? '编辑数据源' : '新增数据源'"
        @submit="handleFormSubmit"
        @close="handleFormClose"
    >
      <!-- 自定义URL字段 -->
      <template #url="{ field, formData }">
        <div style="width:100%;display: flex; gap: 8px; align-items: flex-start;">
          <el-input
            v-model="formData.url"
            type="textarea"
            :rows="3"
            :placeholder="field.placeholder"
            :readonly="field.readonly"
            style="flex: 1;"
          />
          <el-button
            type="primary"
            @click="handleGenerateUrl"
            :disabled="!currentDatasource?.dbType || !currentDatasource?.host || !currentDatasource?.port || !currentDatasource?.databaseName"
            style="margin-top: 0;"
          >
            生成URL
          </el-button>
        </div>
      </template>
      
      <!-- 自定义表单底部额外按钮 -->
      <template #extraButtons>
        <el-button type="primary" @click="testConnectionInDialog" :loading="testing">
          测试连接
        </el-button>
      </template>
    </CommonForm>
  </div>
</template>

<script setup lang="ts">
import {computed, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import CommonTable from '@/components/base/CommonTable/index.vue'
import CommonForm from '@/components/base/CommonForm/index.vue'
import {getApiConfig, getFormFields, getTableColumns, getTableConfig, TableApis} from './index'
import type {DatasourceDTO} from '@/api/codegen'

// 页面数据
const tableRef = ref()
const formRef = ref()
const isEdit = ref(false)
const currentDatasource = ref<DatasourceDTO | null>(null)
const showForm = ref(false)
const selectedRows = ref<DatasourceDTO[]>([])
const submitting = ref(false)
const testing = ref(false)
const testingId = ref<string | null>(null)
const autoGenerateUrl = ref(false) // 是否自动生成URL

// 表单字段配置
const formFields = computed(() => getFormFields(isEdit.value, autoGenerateUrl.value))

// 表格列配置
const tableColumns = computed(() => getTableColumns())

// 表格配置
const tableConfig = computed(() => getTableConfig())

// API配置
const apiConfig = computed(() => getApiConfig())

// 获取数据库类型名称
const getDbTypeName = (dbType: string) => {
  const typeMap: Record<string, string> = {
    mysql: 'MySQL',
    sqlserver: 'SQL Server',
    postgresql: 'PostgreSQL',
    oracle: 'Oracle'
  }
  return typeMap[dbType] || dbType
}

// 获取数据库类型标签类型
const getDbTypeTagType = (dbType: string) => {
  const typeMap: Record<string, string> = {
    mysql: 'success',
    sqlserver: 'warning',
    postgresql: 'info',
    oracle: 'danger'
  }
  return typeMap[dbType] || ''
}

// 新增数据源
const handleAdd = () => {
  isEdit.value = false
  currentDatasource.value = {
    name: '',
    dbType: 'mysql',
    host: 'localhost',
    port: 3306,
    databaseName: '',
    url: '',
    username: '',
    password: '',
    status: 1,
    remark: ''
  }
  autoGenerateUrl.value = true
  showForm.value = true
}

// 编辑数据源
const handleEdit = (row: DatasourceDTO) => {
  isEdit.value = true
  currentDatasource.value = { ...row }
  // 编辑时默认关闭自动生成，因为可能有自定义的URL
  autoGenerateUrl.value = false
  showForm.value = true
}

// 删除数据源
const handleDelete = async (row: DatasourceDTO) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除数据源 "${row.name}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await TableApis.deleteDatasource(row.id!)
    ElMessage.success('删除成功')
    tableRef.value?.refresh()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 测试连接
const testConnection = async (row: DatasourceDTO) => {
  try {
    testingId.value = row.id!
    await TableApis.testConnection(row)
    ElMessage.success('连接测试成功')
  } catch (error: any) {
    console.error('连接测试失败:', error)
    ElMessage.error(error.message || '连接测试失败')
  } finally {
    testingId.value = null
  }
}

// 对话框中测试连接
const testConnectionInDialog = async () => {
  try{
    await formRef.value?.validate();
  }catch (error:any){
    return;
  }

  try {
    if (!currentDatasource.value) return
    testing.value = true
    await TableApis.testConnection(currentDatasource.value)
    ElMessage.success('连接测试成功')
  } catch (error: any) {
    console.error('连接测试失败:', error)
    ElMessage.error(error.message || '连接测试失败')
  } finally {
    testing.value = false
  }
}

// 生成数据库连接URL
const generateDatabaseUrl = () => {
  if (!currentDatasource.value) return ''
  
  const { dbType, host, port, databaseName } = currentDatasource.value
  
  if (!dbType || !host || !port || !databaseName) {
    return ''
  }
  
  let url = ''
  switch (dbType) {
    case 'mysql':
      url = `jdbc:mysql://${host}:${port}/${databaseName}?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai`
      break
    case 'postgresql':
      url = `jdbc:postgresql://${host}:${port}/${databaseName}`
      break
    case 'sqlserver':
      url = `jdbc:sqlserver://${host}:${port};databaseName=${databaseName}`
      break
    case 'oracle':
      url = `jdbc:oracle:thin:@${host}:${port}:${databaseName}`
      break
    default:
      url = ''
  }
  
  return url
}

// 手动生成URL
const handleGenerateUrl = () => {
  if (!currentDatasource.value) return
  
  const url = generateDatabaseUrl()
  if (url) {
    // 确保响应式更新
    currentDatasource.value = {
      ...currentDatasource.value,
      url: url
    }
    ElMessage.success('URL生成成功')
  } else {
    ElMessage.warning('请先填写完整的数据库信息')
  }
}

// 监听数据库类型变化，自动设置默认端口和驱动
watch(
  () => currentDatasource.value?.dbType,
  (newDbType) => {
    if (!currentDatasource.value || isEdit.value) return
    
    // 设置默认端口和驱动
    switch (newDbType) {
      case 'mysql':
        currentDatasource.value.port = 3306
        currentDatasource.value.driverClassName = 'com.mysql.cj.jdbc.Driver'
        break
      case 'postgresql':
        currentDatasource.value.port = 5432
        currentDatasource.value.driverClassName = 'org.postgresql.Driver'
        break
      case 'sqlserver':
        currentDatasource.value.port = 1433
        currentDatasource.value.driverClassName = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
        break
      case 'oracle':
        currentDatasource.value.port = 1521
        currentDatasource.value.driverClassName = 'oracle.jdbc.driver.OracleDriver'
        break
    }
  }
)

// 监听表单字段变化，自动生成URL
watch(
  () => {
    if (!currentDatasource.value) return null
    return {
      dbType: currentDatasource.value.dbType,
      host: currentDatasource.value.host,
      port: currentDatasource.value.port,
      databaseName: currentDatasource.value.databaseName
    }
  },
  (newVal) => {
    if (autoGenerateUrl.value && newVal && currentDatasource.value) {
      const url = generateDatabaseUrl()
      if (url && (!currentDatasource.value.url || currentDatasource.value.url === '')) {
        // 确保响应式更新
        currentDatasource.value = {
          ...currentDatasource.value,
          url: url
        }
      }
    }
  },
  { deep: true }
)

const handleSelectionChange = (selection: DatasourceDTO[]) => {
  selectedRows.value = selection
}

// 表单提交处理
const handleFormSubmit = async (data: DatasourceDTO) => {
  try {
    // 先进行表单校验
    await formRef.value?.validate()
    
    submitting.value = true
    
    if (isEdit.value && currentDatasource.value?.id) {
      // 编辑数据源
      await TableApis.updateDatasource({ ...data, id: currentDatasource.value.id })
      ElMessage.success('数据源更新成功')
    } else {
      // 新增数据源
      await TableApis.createDatasource(data)
      ElMessage.success('数据源创建成功')
    }

    showForm.value = false
    tableRef.value?.refresh()
  } catch (error) {
    console.error('保存数据源失败:', error)
    ElMessage.error('保存数据源失败')
  } finally {
    submitting.value = false
  }
}

// 表单关闭处理
const handleFormClose = () => {
  showForm.value = false
}
</script>

<style scoped>
.table-page {
  height: 100%;
  background: #f5f5f5;
}
</style>